K = kernel
U = user

OBJS = \
    $K/entry.o \
    $K/init.o \
    $K/uart.o \
    $K/console.o \
    $K/print.o \
    $K/cache.o \
    $K/trap.o \
    $K/kernel.o \
    $K/mutex.o \
    $K/kmem.o \
    $K/lib.o \
    $K/mmu.o \
    $K/process.o \
    $K/switch.o \
    $K/timer.o \
    $K/plic.o

# cross compiler and flag set
TOOLPREFIX = riscv64-unknown-elf-
CC = $(TOOLPREFIX)gcc
AS = $(TOOLPREFIX)as
LD = $(TOOLPREFIX)ld
OBJCOPY = $(TOOLPREFIX)objcopy
OBJDUMP = $(TOOLPREFIX)objdump

CFLAGS = -Wall -Werror -O -fno-omit-frame-pointer -ggdb
CFLAGS += -MD
CFLAGS += -mcmodel=medany
CFLAGS += -ffreestanding -fno-common -nostdlib -mno-relax
CFLAGS += -I.
CFLAGS += -fno-stack-protector
CFLAGS += -fno-pie -no-pie
CFLAGS += -DKERNEL_TEST

LDFLAGS = -z max-page-size=4096

all: $K/kernel

# compile kernel
$K/kernel: $(OBJS) $K/kernel.ld
	$(LD) $(LDFLAGS) -T $K/kernel.ld -o $K/kernel.elf $(OBJS) 
	$(OBJCOPY) -O binary $K/kernel.elf $K/kernel.bin
	$(OBJDUMP) -S $K/kernel.elf > $K/kernel.asm

clean: 
	rm -f *.tex *.dvi *.idx *.aux *.log *.ind *.ilg \
	*/*.o */*.d */*.asm */*.sym \
	$K/kernel.elf $K/kernel.bin